package cn.wzg.server.Workers;

import cn.wzg.entity.Request;
import cn.wzg.entity.Response;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

public class WorkThread implements Runnable{
    Socket accept;
    Map<String, Object> serviceprovider;

    public WorkThread(Socket accept, Map<String, Object> serviceprovider) {
        this.accept = accept;
        this.serviceprovider = serviceprovider;
    }

    /***
     * 具体服务器的工作
     */
    @Override
    public void run() {
        //获取输入输出流
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(accept.getOutputStream());
            ObjectInputStream inputStream = new ObjectInputStream(accept.getInputStream());
            Request request = (Request) inputStream.readObject();
            Object object = serviceprovider.get(request.getInterfaceName());
            Method method = object.getClass().getMethod(request.getMethodName(), request.getParamsTypes());
            Object o = method.invoke(object, request.getParams());
            outputStream.writeObject(Response.success(o));
            outputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }


    }
}
